import { useCallback } from "react";
import { ReactFlow, ReactFlowProvider, useReactFlow } from "@xyflow/react";
import "@xyflow/react/dist/style.css";

import { defaultNodes } from "./nodes";
import { defaultEdges } from "./edges";

const edgeOptions = {
  animated: true,
  style: {
    stroke: "white",
  },
};

const connectionLineStyle = { stroke: "white" }; //连接ing，线的color

let nodeId = 0;
function Flow() {
  const reactFlowIns = useReactFlow();
  const handleAddNode = useCallback(() => {
    const id = `${++nodeId}`;
    const newNode = {
      id,
      position: {
        x: Math.random() * 500,
        y: Math.random() * 500,
      },
      data: {
        label: `Node ${id}`,
      },
    };
    reactFlowIns.addNodes(newNode);
  }, [reactFlowIns]);
  return (
    <>
      <ReactFlow
        colorMode="dark"
        defaultNodes={defaultNodes}
        defaultEdges={defaultEdges}
        defaultEdgeOptions={edgeOptions}
        fitView
        style={{
          backgroundColor: "#D3D2E5",
        }}
        connectionLineStyle={connectionLineStyle}
      />
      <button
        onClick={handleAddNode}
        className="btn-add"
        style={{
          position: "absolute",
          zIndex: 10,
          top: "10px",
          left: "10px",
        }}
      >
        add node
      </button>
    </>
  );
}

export default function App() {
  return (
    <ReactFlowProvider>
      <Flow />
    </ReactFlowProvider>
  );
}
